﻿using System.Net.Http.Extensions.Compression.Core.Compressors;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.ExceptionHandling;
using Microsoft.AspNet.WebApi.Extensions.Compression.Server;
using User.Api.Pipeline.ActionFilters;
using User.Api.Pipeline.ExceptionHandlers;
using User.Api.Pipeline.MediaTypeFormatters;

namespace User.Api
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {            
            // Web API configuration and services
            // 打开错误调式信息输出到response
            // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            // 使用自定义TraceWriter，通过CommonLog记录下WebApi管道中的日志
            // config.Services.Replace(typeof(ITraceWriter), new CommonLogTraceWriter());

            // 使用默认TraceWrite
            // var traceWriter = config.EnableSystemDiagnosticsTracing();
            // traceWriter.IsVerbose = true;
            // traceWriter.MinimumLevel = TraceLevel.Debug;
            
            config.Filters.Add(new UserIdRequiredAttribute());

            config.Formatters.Add(new TextPlainFormatter());

            // 添加 webapi 压缩处理，4096byte以下不压缩
            var serverCompressionHandler = new ServerCompressionHandler(4096, new GZipCompressor(),
                new DeflateCompressor());
            config.MessageHandlers.Insert(0, serverCompressionHandler);

            // 全局Exception Logger 和 Handler
            // There can be multiple exception loggers. (By default, no exception loggers are registered.)
            config.Services.Add(typeof(IExceptionLogger), new CommonLogExceptionLogger());

            // There must be exactly one exception handler. (There is a default one that may be replaced.)
            // To make this sample easier to run in a browser, replace the default exception handler with one that sends
            // back text/plain content for all errors.
            config.Services.Replace(typeof(IExceptionHandler), new GenericExceptionHandler());

            // CORS Support
            config.EnableCors(new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true, PreflightMaxAge = 600 });

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
